const app = getApp()
const request = require('../../../utils/request.js');
Page({
  data: {
    id: '',
    name: '',
    type: '',
    typeIndex: 0,
    types: ['秸秆', '稻壳', '玉米芯', '花生壳', '其他'],
    quantity: '',
    price: '',
    unit: '吨',
    unitIndex: 0,
    units: ['吨', '千克', '立方米', '包', '其他'],
    location: '',
    locationCode: '',
    description: '',
    contactName: '',
    contactPhone: '',
    isEdit: false
  },

  onLoad(options) {
    if (options.id) {
      // 编辑模式
      this.setData({
        id: options.id,
        isEdit: true
      });
      this.loadDemandDetail(options.id);
    }
  },

  // 加载需求详情
  loadDemandDetail(id) {
    // 模拟加载数据
    request.request({
      url: `${app.globalData.baseUrl}/api/demands/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        const data = res.data.data
        data.location = data.location.split('/')
        data.locationCode = data.locationCode?JSON.parse(data.locationCode):[],
        this.setData({
          ...data,
        })
      },
      fail: (err) => {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
        console.error('加载商品详情失败:', err)
      },
      complete: () => {
        //
      }
    })
  },

  // 标题输入
  onTitleInput: function (e) {
    this.setData({
      name: e.detail.value
    })
  },

  // 分类选择
  onTypeChange: function (e) {
    this.setData({
      typeIndex: e.detail.value,
      type: this.data.types[e.detail.value]
    })
  },

  // 数量输入
  onQuantityInput: function (e) {
    this.setData({
      quantity: e.detail.value
    })
  },

  // 价格输入
  onPriceInput: function (e) {
    this.setData({
      price: e.detail.value
    })
  },

  // 单位选择
  onUnitChange: function (e) {
    this.setData({
      unitIndex: e.detail.value,
      unit: this.data.units[e.detail.value]
    })
  },

  // 地区输入
  onLocationChange(e) {
    this.setData({
      location: e.detail.value,
      locationCode: e.detail.code
    })
  },

  // 联系人输入
  onContactNameInput: function (e) {
    this.setData({
      contactName: e.detail.value
    })
  },

  // 电话输入
  onContactPhoneInput: function (e) {
    this.setData({
      contactPhone: e.detail.value
    })
  },

  // 描述输入
  onDescriptionInput: function (e) {
    this.setData({
      description: e.detail.value
    })
  },

  // 紧急状态切换
  onUrgentChange: function (e) {
    this.setData({
      isUrgent: e.detail.value
    })
  },

  // 表单验证
  validateForm: function () {
    const {
      name,
      type,
      quantity,
      price,
      unit,
      location,
      locationCode,
      contactName,
      contactPhone,
      description
    } = this.data

    if (!name) {
      wx.showToast({
        title: '请输入需求标题',
        icon: 'none'
      })
      return false
    }

    if (!type) {
      wx.showToast({
        title: '请选择分类',
        icon: 'none'
      })
      return false
    }

    if (!quantity) {
      wx.showToast({
        title: '请输入需求量',
        icon: 'none'
      })
      return false
    }

    if (!price) {
      wx.showToast({
        title: '请输入价格',
        icon: 'none'
      })
      return false
    }

    if (!unit) {
      wx.showToast({
        title: '请选择单位',
        icon: 'none'
      })
      return false
    }

    if (!location) {
      wx.showToast({
        title: '请输入位置',
        icon: 'none'
      })
      return false
    }

    if (!contactName) {
      wx.showToast({
        title: '请输入联系人',
        icon: 'none'
      })
      return false
    }

    if (!contactPhone) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      })
      return false
    }

    if (!description) {
      wx.showToast({
        title: '请输入详细描述',
        icon: 'none'
      })
      return false
    }

    return true
  },

  // 提交需求
  submitDemand: function () {
    if (!this.validateForm()) return

    if (!app.getGlobalToken()) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    wx.showLoading({
      title: '发布中...',
    })

    const {
      id,
      name,
      type,
      quantity,
      price,
      unit,
      location,
      locationCode,
      contactName,
      contactPhone,
      description
    } = this.data

    request.request({
      url: `${app.globalData.baseUrl}/api/demands`,
      method: 'POST',
      data: {
        id,
        name,
        type,
        quantity: parseFloat(quantity),
        price: parseFloat(price),
        unit,
        location: location.join('/'),
        locationCode: JSON.stringify(locationCode),
        contactName,
        contactPhone,
        description,
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '发布成功',
            icon: 'success'
          })
          // 发布成功后返回上一页
          app.globalData.needRefresh = true;
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.data.message || '发布失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
})